import { Injectable, NestInterceptor, ExecutionContext, CallHandler, BadGatewayException, HttpStatus } from '@nestjs/common';
import { Observable, throwError, of } from 'rxjs';
import { tap, map, catchError } from 'rxjs/operators';
import utils from 'src/common/utils';
import { wx_user_rela_code } from 'src/setting';

@Injectable()
export class ValidTokenInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context.switchToHttp().getRequest();
    const res = context.switchToHttp().getResponse();
    let wx_user = req.headers.wx_user
    let wx_user_token = req.headers.wx_user_token
    let unauthor = (message) => {
      const status = HttpStatus.UNAUTHORIZED;
      const errorResponse = {
        message: message,
        status: status, // 自定义code
        url: req.originalUrl, // 错误的url地址
      };
      return of(errorResponse);
    }
    if(!wx_user || !wx_user_token) {
      let message = !wx_user ? '无效用户' : '非法用户'
      return unauthor(message)
    }else{
      let gender_token = utils.md5(utils.user_token_key + wx_user)
      if(gender_token != wx_user_token){
        return unauthor('非法用户');
      }
      if(wx_user === wx_user_rela_code.question.wx_user){
        req.headers.wx_user = wx_user_rela_code.question.rela_wx_user
      }else if(wx_user === wx_user_rela_code.answer.wx_user){
        req.headers.wx_user = wx_user_rela_code.answer.rela_wx_user
      }
      return next.handle().pipe(
        map(data => {
          return data
        })
      );
    }
  }
}
